<template>
  <div v-if="date">
    <table class="timelog-table" cellpadding="0" cellspacing="0">
      <tbody>
        <tr>
          <td width="200px">日期:</td>
          <td>{{ date }}</td>
        </tr>
        <tr>
          <td>项目工作安排:</td>
          <td></td>
        </tr>
        <tr>
          <td>首次打卡时间:</td>
          <td v-if="isValid == 1">
            <el-tag class="tag" v-if="clockinTimeStart == '-'" type="danger" @click="handlerClickBtnGoClockIn">未打卡</el-tag>
            <template v-else>{{ clockinTimeStart }}</template>
          </td>
          <td v-else-if="isValid == 2">{{ clockinTimeStart }}</td>
        </tr>
        <tr>
          <td>最后一次打卡时间:</td>
          <td v-if="isValid == 1">
            <el-tag class="tag" v-if="clockinTimeEnd == '-'" type="danger" @click="handlerClickBtnGoClockIn">未打卡</el-tag>
            <template v-else>{{ clockinTimeEnd }}</template>
          </td>
          <td v-else-if="isValid == 2">{{ clockinTimeEnd }}</td>
        </tr>
        <tr>
          <td>打卡总时长:</td>
          <!-- <td>6 小时 40 分钟</td> -->
          <td></td>
        </tr>
      </tbody>
    </table>
    <table class="timelog-table" cellpadding="1" cellspacing="1">
      <tbody>
        <tr>
          <td width="200px">要求工作总时长:</td>
          <td>{{ totalWorkTime }} 小时</td>
        </tr>
        <tr>
          <td>要求打卡总时长:</td>
          <td v-show="false">{{ totalClockInTime }} 小时</td>
        </tr>
        <tr>
          <td>要求打卡起止时间:</td>
          <td>{{ startWorkTime }}-{{ endWorkTime }}</td>
        </tr>
        <tr>
          <td>午休时间:</td>
          <td>{{ startLunchTime }}-{{ endLunchTime }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { useUsersStore } from '../../stores'
import * as utils from '../../utils'
import http from '../../http'
import { useRouter } from 'vue-router'

const router = useRouter()

const props = defineProps({
  date: { type: String || Date, default: '' },
  startWorkTime: { type: String || Date, default: '' },
  endWorkTime: { type: String || Date, default: '' },
  startLunchTime: { type: String || Date, default: '' },
  endLunchTime: { type: String || Date, default: '' },
})

// 工作总时长、打卡总时长、起止时间、午休时间
const totalClockInTime = ref(0)
const clockinTimeStart = ref('')
const clockinTimeEnd = ref('')
// const clockInPeriod = ref(0)
// const noonBreakTime = ref(0)

onMounted(() => {
  // getClockinCategoryInfo()
  // console.log('props.date', props.date)
})

watch(
  () => props.date,
  () => {
    getClockinCategoryInfo()
  },
  { deep: true }
)

// 计算两个时间之间的小时差
const totalWorkTime = computed(() => {
  // 示例用法
  const startWorkTime = props.date + ' ' + props.startWorkTime
  const endWorkTime = props.date + ' ' + props.endWorkTime
  const startLunchTime = props.date + ' ' + props.startLunchTime
  const endLunchTime = props.date + ' ' + props.endLunchTime

  const hourDiff = getHourDiff(startWorkTime, endWorkTime, startLunchTime, endLunchTime)
  // console.log('hourDiff', hourDiff)
  return hourDiff.num
})

const handlerClickBtnGoClockIn = () => {
  router.push({ name: 'Clockin' })
}

/**
 * 获取考勤列表
 *
 * @returns {Promise<void>}
 */
const getClockinCategoryInfo = async () => {
  const currentUser = useUsersStore().getAllState()
  const date = new Date(props.date)
  const params = {
    userName: currentUser.username,
    pageSize: 99999,
    startClockinDate: utils.formatDate(date, 'yyyy-MM-dd'),
    endClockinDate: utils.formatDate(date, 'yyyy-MM-dd'),
  }
  const { rows } = await http({
    method: 'GET',
    path: '/dev-api/oa/clockin/list',
    params,
  })

  const clockinTimeStartItem = rows.find((row: any) => row.clockinCategory == 0)
  const clockinTimeEndItem = rows.find((row: any) => row.clockinCategory == 1)

  if (clockinTimeStartItem) {
    clockinTimeStart.value = utils.formatDate(new Date(clockinTimeStartItem.clockinTime), 'HH:mm')
  } else {
    clockinTimeStart.value = '-'
  }
  if (clockinTimeEndItem) {
    clockinTimeEnd.value = utils.formatDate(new Date(clockinTimeEndItem.clockinTime), 'HH:mm')
  } else {
    clockinTimeEnd.value = '-'
  }
}

// 是否是有效的日期
const isValid = computed(() => {
  return utils.isDateLessThanOrEqual(new Date(props.date), new Date())
})
/**
 * 计算工作时长
 *
 * @param startWorkTime 开始工作时间（字符串格式）
 * @param endWorkTime 结束工作时间（字符串格式）
 * @param startLunchTime 午餐开始时间（字符串格式，可选）
 * @param endLunchTime 午餐结束时间（字符串格式，可选）
 * @returns 包含工作时长的小时和分钟的对象
 */
const getHourDiff = (startWorkTime: string, endWorkTime: string, startLunchTime: string | null = null, endLunchTime: string | null = null) => {
  const start = new Date(startWorkTime) as any
  const end = new Date(endWorkTime) as any

  let totalWorkingHours = (end - start) / (1000 * 60 * 60) // 总工作时间（小时）

  // 如果午餐时间参数存在，则扣除午餐时间
  if (startLunchTime && endLunchTime) {
    const lunchStart = new Date(startLunchTime) as any
    const lunchEnd = new Date(endLunchTime) as any
    let lunchBreakHours = (lunchEnd - lunchStart) / (1000 * 60 * 60) // 午餐时间（小时）
    totalWorkingHours -= lunchBreakHours
  }
  // 根据传入的格式参数返回不同的格式
  const hours = Math.floor(totalWorkingHours)
  const minutes = Math.round((totalWorkingHours - hours) * 60)

  const result = {
    num: totalWorkingHours.toFixed(2),
    text: `${hours} 小时 ${minutes} 分钟`,
  }
  return result
}
</script>
<style scoped lang="scss">
.timelog-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #ebeef5;
  tr {
    td {
      text-align: left;
      padding: 4px 12px;
      border: 1px solid #ebeef5;
    }
  }
  & + .timelog-table {
    margin-top: 20px;
  }
  .tag {
    cursor: pointer;
  }
}
</style>
